package com.shiyi.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shiyi.common.R;
import com.shiyi.domain.Message;
import com.shiyi.domain.User;
import com.shiyi.mapper.MessageMapper;
import com.shiyi.mapper.UserMapper;
import com.shiyi.service.MessageService;
import com.shiyi.utils.PageUtils;
import com.shiyi.vo.MessageListVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author: 拾壹
 * @date: 2023/12/13
 * @describe:
 */
@Service
@RequiredArgsConstructor
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    private final UserMapper userMapper;

    @Override
    public R selectMessageList(Integer userId,Integer receiverId, Integer isGroup) {
        Page<MessageListVO> page = baseMapper.selectMessageList(new Page<>(PageUtils.getPageNo(),PageUtils.getPageSize()),userId,receiverId,isGroup);
        for (MessageListVO messageListVO : page.getRecords()) {
            if (messageListVO.getIsGroup() == 1) {
                Integer senderId = messageListVO.getSenderId();
                User user = userMapper.selectById(senderId);
                messageListVO.setSenderAvatar(user.getAvatar());
                continue;
            }
            Integer senderId = messageListVO.getSenderId();
            User user = userMapper.selectById(senderId);
            messageListVO.setSenderAvatar(user.getAvatar());
            messageListVO.setSenderNickname(user.getNickname());
        }
        return R.success(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertMessage(Message message) {
        baseMapper.insert(message);
    }
}
